<template>
  <view>
    <c-popup v-model="showShare" position="center">
      <view class="share-popup">
        <view>
          <image :src="shareImg" mode="widthFix" style="width: 690rpx" />
        </view>
        <view class="flex-around" style="margin-top: 15px">
          <view hover-class="view-hover" class="share-btn">
            <button class="clearbtn" open-type="share">
              <view>
                <image src="/assets/imgs/share-wx.png" class="img"></image>
                <view>分享好友</view>
              </view>
            </button>
          </view>
          <view hover-class="view-hover" @tap="onSaveImage" class="share-btn">
            <image src="/assets/imgs/share-save.png" class="img"></image>
            <view>保存图片</view>
          </view>
        </view>
      </view>
    </c-popup>
    <c-canvas ref="canvas" style="position: absolute; left: -9999px; top: -9999px" :max-width="690"></c-canvas>
  </view>
</template>
<script setup>
import { CCanvas, CPopup } from '@/components';
import { ref, inject, shallowRef } from 'vue';
import { View, Button, Image } from '@tarojs/components';
import { afterLogin, builderImgUrl, builderAttrs, builderQrcode } from '@/hooks';
import { useShareAppMessage, hideShareMenu, saveImageToPhotosAlbum, useReady, getImageInfo } from '@tarojs/taro';
import toast from '@/utils/toast';
import api from '@/api';
import { isObject } from 'lodash';
import { authorizeKey } from '@/constants';
const props = defineProps({
  code: String,
  path: String,
  data: Object,
  appendId: String
});

const authorizeError = inject(authorizeKey);
const canvas = shallowRef();
const showShare = ref(false);
const poster = ref(null);
const userInfo = ref(null);
const shareImg = ref('');
const loadPoster = async () => {
  poster.value = (await api.bus.poster()).find(a => a.posterCode == props.code);
  if (poster.value) {
    getImageInfo({
      src: builderImgUrl(poster.value.backgroundImg),
      success(data) {
        poster.value.width = data.width;
        poster.value.height = data.height;
        poster.value.backgroundImg = data.path;
      }
    });
  }
};
const builderText = (text, args) => {
  if (isObject(args)) {
    for (const key in args) {
      const element = args[key];
      text = text.replaceAll(`{${key}}`, element);
    }
  }
  return text;
};

useReady(async () => {
  await afterLogin();
  loadPoster();
});
const getArgs = () => {
  return {
    ...userInfo.value,
    ...(props.data ?? {})
  };
};

const onSaveImage = async () => {
  saveImageToPhotosAlbum({
    filePath: shareImg.value,
    success() {
      showShare.value = false;
      toast.success('保存成功');
    },
    fail(e) {
      authorizeError.value = e;
    }
  });
};

defineExpose({
  poster,
  show() {
    if (!poster.value) return toast.error('未设置分享');
    if (shareImg.value) {
      showShare.value = true;
      return;
    }
    toast.loading.lock(async () => {
      userInfo.value = await api.user.userGetInfo();
      const attrs = builderAttrs(poster.value.contexts, {
        ...getArgs(),
        qrcode: builderQrcode(props.path, props.appendId)
      });
      await canvas.value.load(poster.value.backgroundImg, poster.value.width, poster.value.height, attrs);
      shareImg.value = await canvas.value.saveImage();
      showShare.value = true;
    });
  }
});

hideShareMenu();
useShareAppMessage(() => {
  showShare.value = false;
  const url = `${props.path}?uid=${userInfo.value.userId}&id=${props.appendId}`;
  const title = builderText(poster.value.shareTitle, getArgs());
  return {
    title: title,
    imageUrl: builderImgUrl(poster.value.backgroundImg),
    path: url,
    promise: new Promise(resolve => {
      canvas.value.saveImage().then(filePath => {
        resolve({
          title: title,
          imageUrl: filePath,
          path: url
        });
      });
    })
  };
});
</script>
<style lang="scss">
.share-popup {
  border-radius: 10px;
  padding: 0 0 20px;
  .share-btn {
    width: 140rpx;
    text-align: center;
    font-size: 24px;
    color: var(--color-gray);
    .img {
      height: 80rpx;
      width: 80rpx;
      margin: 0 auto 15rpx;
    }
  }
}
</style>
